<template>
  <el-container>
  <!-- <el-header>购买字体</el-header> -->
  <!-- <el-aside width="200px">
    <iframe v-show="show" id="show-iframe"  frameborder=0 name="showHere" scrolling=auto :src="ip" style="width: 450px;height: 800px;">
  </iframe>
  </el-aside> -->
  <el-main>
      <div >
      <el-row :gutter="20">
      <el-col :span="8">
      <p class="title" id = "ptitle">在线设备{{onlineDev}} 台</p>
      <div class="card dbsx" id = "coldiv">
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="item,index in dev" :label="item.ip" :disabled ="checkgroup(item)" >  <el-tooltip class="item" effect="dark" :content="tipmsg(item)" placement="top"><p>{{item.ip}}</p></el-tooltip></el-checkbox>
            <!-- disabled = v-if="item.groups==''" -->
          </el-checkbox-group>
      
        <el-dialog
          title="提示"
          :visible.sync="dialogVisible"
          width="30%"
          :before-close="handleClose">
          <span>分组信息</span>
          <el-input v-model="msg"></el-input>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="upGroup">确 定</el-button>
          </span>
        </el-dialog>
          
        <el-button @click="ShowIp" class = "gbtn"> 分组 </el-button>
        </div>
      </el-col>
      <el-col :span="8">
        <p class="title" id = "ptitle">任务列表</p>

        
        <div class="card dbsx" id = "coldiv">
            <div style="text-align: center;">
              任务列表
            <el-table
            :data="joblist"
            style="width: 100%">
            <el-table-column
              label="任务ID"
              prop="jobid">
            </el-table-column>
            <el-table-column
              label="字体名"
              prop="font">
            </el-table-column>
            <el-table-column
              label="分组"
              prop="groups">
            </el-table-column>
            <el-table-column
              label="渠道"
              prop="platform">
            </el-table-column>
            <el-table-column
              label="状态"
              prop="status">
            </el-table-column>

            <el-table-column
              label="每日任务"
              prop="IsDay">
            </el-table-column>
            <el-table-column
              align="right">
              <template slot="header" slot-scope="scope">
                <el-input
                  v-model="search"
                  size="mini"
                  placeholder="输入关键字搜索"/>
              </template>
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleEdit(scope.$index, scope.row)">Edit</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">Delete</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="downFontrunApi(scope.$index, scope.row)">执行任务</el-button>

                  
              </template>
            </el-table-column>
          </el-table>
              </div>

              <el-button @click="jobdialogshow">添加任务</el-button>
              <el-dialog
                title="添加任务"
                :visible.sync="job_S"
                width="30%"
                style="text-align: center;"
                :before-close="jobhandlerClose">
              <el-form>
              
              <div>
              <el-form-item label="设备分组">
                 <el-radio v-for="item,index in  grouplist" v-model="groups" :label="item.name">{{item.name}}</el-radio>
              </el-form-item>
              </div>
              
              <div>
              <el-form-item label="渠道" >
              <el-radio-group v-model="apps" @change="Fontbyfroms">
  
              <el-radio  label="oppo"  style="margin-top:10%" >oppo</el-radio>
              <el-radio  label="huawei"  style="margin-top:10%" >华为</el-radio>
              <el-radio  label="vivo"  style="margin-top:10%">vivo</el-radio>
              </el-radio-group>
              </el-form-item>
              </div>

              <div >
              <el-form-item label="字体">
                <el-select v-model="font" filterable clear  allow-create  placeholder="请选择字体">
                  <el-option v-for="item in fontlist"  :label="item.name" :value="item.name"></el-option>
                </el-select>
              </el-form-item>
              </div>
              </el-form>
              <el-button @click="Addjob">提交</el-button>
              </el-dialog>
              
              
        

        </div>
      </el-col>
      <el-col :span="8">
        <p class="title" id = "ptitle">日志</p>
        
        <ul>

        <div class="card kjfs" id = "coldiv">
        <li>
          <div style="text-align: center;">
          <span id = "ms"></span>
          </div>
        </li>
        </div>
        </ul>
      </el-col>
    </el-row>
  </div>
  <el-divider content-position="left">下面的是新功能</el-divider>

 

  
  <!-- <el-avatar size="medium" src="http://192.168.248.249:8090/static/usr/1.jpg"></el-avatar> -->
        
  
  </el-main>
  

  </el-container>

</template>

              
<script>
import axios from 'axios';

import { device,act_run,orders,devupdate,atx,adb,DevGroup,GetDevGroup,Fontbyfrom,addjob,GetJob,downFontrun } from '../../api/autopay';
// import loading from '../views/loading'
export default {
    name: 'autopay',
    data() {
        return {
            search:"",
            dev: [],
            checkAll: false,
            groups: "",
            isIndeterminate: true,
            checkedCities: [],
            checkList: [],
            show: false,
            dialogVisible: false,
            loadshow: true,
            job_S:false,
            url: "",
            onlineDev: 0,
            fontlist: [],
            joblist:[],
            font:"",
            grouplist :[],
            msg: "",
            ip: "",
            res: "",
            logip:"192.168.248.179",
            apps: 'oppo',
            centerDialogVisible: false,
            loading: false,
            
        }
    },
    // components: {
      
    // },//components
    mounted:function () {
        
        // if (this.timer){
        //     clearInterval(this.timer);
        // }else{
        //    this.timer = setInterval(()=>{
        //     this.DeviceUp();
        //    },100000); 
        // }
        this.GetDevice();
        // this.GetDevGroup()
        // this.Fontbyfrom()
        this.getmyip();
        this.GetJobs();
        // this.ShowLog()
        
    },
    created(){
           //页面刚进入时开启长连接
            // this.initWebSocket()

    },
　　destroyed: function() {
　　　　//页面销毁时关闭长连接
　　　　this.websocketclose();
　　},
    methods: {
      jobdialogshow(){
        var that = this;
        that.job_S = true;
        that.GetDevice();
        that.GetDevGroup();
        that.Fontbyfroms();
      },
      downFontrunApi(index, row){
        console.log( row);
        var fonts = [];
        var IpList = [];
        fonts.push(row.font);
        IpList.push(row.ip)
        let par = {"Count": row.runnum,"Distribution": false,"Fonts": fonts,"Ips": IpList,"IsDay": true,"JobName": row.jobid,"Platform": row.platform,"Status": "-1","Type": row.types, "IsPay": row.IsPay,"IsDown": row.IsDown}


        // let par ={
        //   "Count": "string",
        //   "Distribution": true,
        //   "Fonts":fonts,
        //   "ID": 0,
        //   "Ips":IpList,
        //   "IsDay": true,
        //   "IsDown": true,
        //   "IsPay": true,
        //   "JobName": row.jobid,
        //   "Platform": "string",
        //   "Status": "string",
        //   "Type": "string"
        // }
        downFontrun(par).then(res =>{
          let {code,msg,data} = res;
          if (code == 200) {
            that.$message("任务添加成功")
            // that.job_S = false;
            // that.GetJobs();
          }else{
            // that.job_S = true;
            that.$message.error(data);
          }
        })
      },
      GetJobs() {
        GetJob().then(res =>{
          let {code,msg,data} = res;
          if (code == 200){
            this.joblist = data;
          }
        }
        )
      },
      Addjob(){
        var that = this;
        let par = {
          "count": 1000,
          "name": that.font,
          "platform": that.apps,
          "groups": that.groups,
          "types": "1"
        }
        addjob(par).then(res =>{
          let {code,msg,data} = res;
          if (code == 200) {
            that.$message("任务添加成功")
            that.job_S = false;
            that.GetJobs();
          }else{
            that.job_S = true;
            that.$message.error(data);
          }
        })
      },
      tipmsg(item){
        if (item.groups == ""){
          return "未分组"
        }else{
          return "分组为"+item.groups
        }

      },
      jobhandlerClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});

      },
      GetDevGroup() {

        GetDevGroup().then( res =>{

          let { code, msg, data } = res;
          console.log(code, msg, data);
          if (code == 200){
            this.grouplist = data;
          }
        } )
      },
      Fontbyfroms() {
        console.log(this.apps);
        var par = {"platfrom":this.apps}
        Fontbyfrom(par).then( res => {
          let { code,msg,data } = res;
          console.log(code,msg,data);
          if (code == 200){
            this.fontlist = data;
            this.font = "";
          }
        }
          )
      
      },
      checkgroup(item){

        if (item.groups == ""){
          return false
        }else{
          return true
        }
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      initWebSocket(){ //初始化weosocket
          const wsuri = `ws://`+this.logip+`:8090/log`//这个地址由后端童鞋提供
          this.websock = new WebSocket(wsuri);
          this.websock.onmessage = this.websocketonmessage;
          this.websock.onopen = this.websocketonopen;
          this.websock.onerror = this.websocketonerror;
          this.websock.onclose = this.websocketclose;
        },
        websocketonopen(){ //连接建立之后执行send方法发送数据
          this.websocketsend(this.user)
          // console.log(111);
        },
        websocketonerror(){//连接建立失败重连
          this.initWebSocket()
        },
        websocketonmessage(evt){
          let _this = this //数据接收

           
          var tmp = evt.data.replace(/\\/g,"%");
          var tmp1 = tmp.replace("[{","");
          var tmp2 = tmp1.replace("}]","");
          var str = tmp2.replace("%n","");
          document.getElementById('ms').innerText = unescape(str)+"\n";
          

          // if ( evt.data.indexOf("\\u") != -1) {
          //     document.getElementById('ms').innerText= this.Hanzi(evt.data);
          // }else{
          //     // console.log(evt.data);
          //     document.getElementById('ms').innerText= evt.data;
          // }
          
        },
        websocketsend(Data){//数据发送
          this.websock.send(Data)
        },
        websocketclose(e){  //关闭
          // console.log('断开连接', e)
        },
        upGroup(){
          var that = this;
          that.dialogVisible = false;
          
          let par = {"iplist":that.checkedCities,"group":that.msg};
          console.log(par);
          DevGroup(par).then( res =>{
            let { code, msg, data } = res;
              if (code == 200){
                this.$message(
                  {
                    message: "更新成功",
                    type: 'success'
                  }
                )
                that.msg = "";
                that.checkedCities = [];
              }else{
                this.$message.error("数据更新失败");
              }

            }).catch(() => {
                this.$message.error("数据请求失败");
          });
        },
        ShowIp(){
          
          var that = this;
          that.dialogVisible = true;
          
        },
        GetDevice() {
            device().then(res => {
              let { code, msg, data } = res;
            
              if (code == 200){
                  if (data != undefined && data.length == 0) {
                  this.$message("无在线设备，请确认设备已连接");
                  }
                // this.loadshow = false;
                this.dev = data;
                this.onlineDev = data.length;
              }else{
                this.$message(data);
              }
              
            }).catch( () => {
                    this.$message.error("数据请求失败");
                });;
        },
        getmyip(){
          var os = require('os'), ipaddress = '', ifaces = os.networkInterfaces() // 获取本机ip
          this.$message(ifaces);
          out:
          for (var i in ifaces) {
            for (var j in ifaces[i]) {
              var val = ifaces[i][j]

              if (val.family === 'IPv4' && val.address !== '127.0.0.1') {
                ipaddress = val.address
                break out
              }
            }
          }
          // module.exports = ipaddress
          
          
        },
        actRun() {
            
            this.res = "";
    

            if (this.dev!=undefined && this.dev.lenth != 0) {
              
              for (var i =  0; i < this.dev.length; i++) {
                if (this.dev[i].Online == true) {
                  if (this.apps == "huawei" &&  (this.dev[i].name == this.apps || this.dev[i].name == "HONOR")){
                    this.url = "http://"+this.dev[i].ip+":7912/remote";
                    this.ip = this.dev[i].ip;
                  }else if (this.dev[i].name.toLowerCase() == this.apps){
                    this.url = "http://"+this.dev[i].ip+":7912/remote";
                    this.ip = this.dev[i].ip;
                  }
                  
                  
                }
              }
              if(this.ip != ""){
                this.show = true;
                this.centerDialogVisible = true;
                let par = {"app":this.apps,"ip":this.ip };
                act_run(par).then(res => {
                let { code, msg, data } = res;
                this.res = data;
                console.log(data);
                if (code != 200) {
                  this.$message.error(data);
                  this.show = false;
                  this.centerDialogVisible = false;
                }

                }
                ).catch( () => {
                    this.$message.error("数据请求失败");
                });;
              }else{

                this.$message.error(this.apps+"无在线设备");
              }
              
            }
            else{
              this.$message.error("无在线设备，请确认设备已连接，点击更新设备按钮重新获取设备列表");
            }
        },

        Hanzi(msg) {
          msg = msg.split("\\u");
          var str ='';
        
          for(var i=0;i<msg.length;i++){
            console.log(msg[i]+"\n");
            str+=String.fromCharCode(parseInt(msg[i],16).toString(10));
              
          } 

          return str+"\n";
        },
        Atx(){
          this.loading = true;
          atx().then(res => {
            let { code, msg, data } = res;
            if (code == 200) {
              this.$message(data);
              this.GetDevice();
            }else{
              this.$message.error(data);
            }
          }).catch( () => {
                    this.$message.error("数据请求失败");
                });;
          
          
          this.loading = false;
        },
        handleEdit(index, row) {
          console.log(index, row);
        },
        handleDelete(index, row) {
          console.log(index, row);
        },
        handleCheckAllChange(val) {
         
          for (var i = this.dev.length - 1; i >= 0; i--) {
            this.checkList.push(this.dev[i].ip)
          }
          this.checkedCities = val ? this.checkList : [];
          this.isIndeterminate = false;
        },
        handleCheckedCitiesChange(value) {
          let checkedCount = value.length;
          this.checkAll = checkedCount === this.dev.length;
          this.isIndeterminate = checkedCount > 0 && checkedCount < this.dev.length;
        },
        DeviceUp(){
          this.loading = true;
          devupdate().then(res => {
            let { code, msg, data } = res;
            if (code == 200) {
              this.$message("设备信息已更新");
            }else{
              this.$message.error(data);
            }
          }).catch( () => {
                    this.$message.error("数据请求失败");
                });;
          
          this.GetDevice();
          this.loading = false;
        },
        
      
    }//
}

</script>

<style>
  /*html, body {
    margin: 0;
    background-color: hsla(0,0%,100%,.9);
    width: 100%;
    height: 100%;
  }*/
  .gbtn{
    text-align: center;
  }
  .el-header, .el-footer {
    background-color: rgba(87, 163, 243, 0.09);
    color: #333;
    text-align: center;
    line-height: 60px;
  }
  
  .el-aside {
    background-color: #D3DCE6;
    color: #333;
    text-align: center;
    line-height: 400px;
  }
/*  
 .el-main {
    background-color: rgba(233, 238, 243, 0.23);
    color: #333;
    text-align: center;
    line-height: 160px;
  }*/
  
/*  body > .el-container {
    margin-bottom: 40px;
    background: url(../img/banner2.jpg)no-repeat center;
    background-size: cover;
  }
*/
  .el-container:nth-child(5) .el-aside,
  .el-container:nth-child(6) .el-aside {
    line-height: 260px;
  }
  
  .el-container:nth-child(7) .el-aside {
    line-height: 320px;
  }
  .time {
    font-size: 13px;
    color: #999;
  }
  
  .bottom {
    margin-top: 13px;
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }
/*  #cols {
    background-color: rgba(233, 238, 243, 0.23);
  }*/
  .image {
    width: 100%;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
      display: table;
      content: "";
  }
  
  .clearfix:after {
      clear: both
  }
  .colip{
    height: 480px;
  }
  #coldiv{
    height: 480px;
    margin-top: 10px;
    margin-right:2px;
    margin-left: 10px;
    background-color: rgba(233, 238, 243, 0.23);
  }
  #ptitle{
    margin-left: 50%;
  }
  
</style>
